//
//  ChengJiYiChangVC.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/6/13.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "ChengJiYiChangVC.h"
#import "CJYCTableHeaderView.h"
#import "SYRequestAPI+TongYong.h"
#import "CJPMYiChangModel.h"
#import "ZXFDCreateClassView.h"

@interface ChengJiYiChangVC (){
    //YEs :上升  NO：下降
    BOOL isUp;
}
@property (nonatomic, strong) NSMutableArray *upArray;
@property (nonatomic, strong) NSMutableArray *downArray;
@property (nonatomic, strong) ZXFDCreateClassView *createClassView;

@property (nonatomic, copy) NSString *cjClassName;
@property (nonatomic, copy) NSString *fdbjId;


@end

@implementation ChengJiYiChangVC
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    isUp = YES;
    _upArray = [NSMutableArray new];
    _downArray = [NSMutableArray new];
    // Do any additional setup after loading the view from its nib.
    
}
//删除掉
- (void)dismissChuangJianBanJi{
    [UIView animateWithDuration:0.5 animations:^{
        self->_createClassView.frame = CGRectMake(0, self.view.frame.size.width,self.view.frame.size.width,self.view.frame.size.height);
    } completion:^(BOOL finished) {
        [self->_createClassView removeFromSuperview];
    }];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"ZaiXianFuDaoTianJiaXueShengView" object:nil];
}
- (void)initSubView{
    _className.text = @"";
    self.tableView.layer.cornerRadius = 5;
    self.tableView.layer.masksToBounds = YES;
    self.tableView.layer.borderWidth = 1;
    self.tableView.layer.borderColor = LINCOLOR.CGColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[ChengJiYiChangCell class] forCellReuseIdentifier:@"cell"];
    _backView.backgroundColor = MAINBACKCOLOR;
    [_backView addSubview:self.switchView];
    _classNameTitle.textColor = TITLECOLOR;
    _className.textColor = TITLECOLOR;
    [_switchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self->_backView.mas_centerX);
        make.centerY.equalTo(self->_backView.mas_centerY);
        make.width.equalTo(@300);
        make.height.equalTo(@50);
    }];
//    [self getPaiMingChengJiYiChangUp];
//    [self getPaiMingChengJiYiChangDown];
    __weak typeof(self)weakSelf = self;
    _switchView.upBlock = ^{
        self->isUp = YES;
        [weakSelf.tableView reloadData];
    };
    _switchView.downBlock = ^{
        self->isUp = NO;
        [weakSelf getPaiMingChengJiYiChangDown];
       // [weakSelf.tableView reloadData];
    };
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dismissChuangJianBanJi) name:@"ZaiXianFuDaoTianJiaXueShengView" object:nil];
    
}

- (CJYCSwitchView *)switchView{
    if (!_switchView) {
        CJYCSwitchView *view = [[CJYCSwitchView alloc]initWithFrame:CGRectMake(_backView.frame.size.width/2-150, 0, 300,50)];
        view.backgroundColor = [UIColor clearColor];
        _switchView = view;
    }
    return _switchView;
}
- (CJYCAlertView *)alertView{
    if (!_alertView) {
        CJYCAlertView *alertView = [[CJYCAlertView alloc]initWithFrame:CGRectMake(0, 0, 500, 120) andArray:@[@"考试名",@"时间",@"考试分数",@"排名"] andMessageID:self.model.msgId andModel:_studentModel];
        alertView.backgroundColor = [UIColor whiteColor];
        _alertView = alertView;
    }
    return _alertView;
}
- (UIView *)maskView{
    if (!_maskView) {
        UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
        maskView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.1];
        _maskView = maskView;
    }
    return _maskView;
}
- (IBAction)closeClick:(id)sender {
    [self.view removeFromSuperview];
}
- (void)addAlert:(CJPMYiChangModel *)model{
    _studentModel = model;
    [self.view addSubview:self.maskView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissAlertView)];
    [_maskView addGestureRecognizer:tap];
    [self.view addSubview:self.alertView];
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.width.equalTo(@500);
        make.height.equalTo(@500);
    }];
}
- (void)dismissAlertView{
    [_maskView removeFromSuperview];
    [_alertView removeFromSuperview];
    _alertView = nil;
    _maskView = nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isUp) {
        return _upArray.count;
    }else{
        return _downArray.count;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChengJiYiChangCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[ChengJiYiChangCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row%2 == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        cell.backgroundColor = CONTENTBACKCOLOR;
    }
    cell.index = (int)indexPath.row;
    __weak typeof(self)weakSelf = self;
    
    
    if (isUp) {//上升异常
        CJPMYiChangModel *model = self->_upArray[indexPath.row];
        cell.buttonView.block = ^(int index) {
            
            [weakSelf addAlert:model];
        };
        
        NSInteger change = [model.OrderTotalChange integerValue];
        
        if (change < 0) {
            change = ~(change - 1);
        }
        NSArray *uparray = @[model.StudentName,model.Serial,model.ExamSort,SJStringWithFormat(change)];
        [cell reloadViewArray:uparray];
        
    }else{
        cell.buttonView.callBlock = ^(int index) {
            CJPMYiChangModel *model = self->_downArray[index];
            [weakSelf callPhone:model];
        };
        CJPMYiChangModel *model = _downArray[indexPath.row];
        
        
        NSInteger change = [model.OrderTotalChange integerValue];
        
        if (change < 0) {
            change = ~(change - 1);
        }
        NSArray *uparray = @[model.StudentName,model.Serial,model.ExamSort,SJStringWithFormat(change)];
        [cell reloadViewArray:uparray];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CJYCTableHeaderView *headerView = [[CJYCTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width-20, 50)];
    return headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.view.frame.size.width , 50)];
    view.backgroundColor = [UIColor whiteColor];
//    if (!_createClassButton) {
         [view addSubview:self.createClassButton];
        [_createClassButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view.mas_centerX);
            make.width.equalTo(@80);
            make.height.equalTo(@40);
            make.top.equalTo(view.mas_top).offset(10);
        }];
//    }
    return view;
}
#pragma mark - 打电话
- (void)callPhone:(CJPMYiChangModel *)model{
//    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@",model.Phone];UIWebView * callWebview = [[UIWebView alloc] init];[callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];[self.view addSubview:callWebview];
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@",model.Phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark - 创建班级
- (UIButton *)createClassButton{
    if (!_createClassButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"创建班级" forState:UIControlStateNormal];
        [button setTitleColor:SELECTEDCOLOR forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor whiteColor]];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.layer.cornerRadius = 2;
        button.layer.borderWidth = 1;
        button.layer.borderColor = SELECTEDCOLOR.CGColor;
        button.layer.masksToBounds = YES;
        [button addTarget:self action:@selector(createClassClick:) forControlEvents:UIControlEventTouchUpInside];
        _createClassButton = button;
    }
    return _createClassButton;
}
#pragma mark - 前往创建班级
- (void)createClassClick:(UIButton *)sender{
    NSLog(@"前往创建班级");
    
    _createClassView = [[ZXFDCreateClassView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _createClassView.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
    _createClassView.mesgId = self.model.msgId;
    _createClassView.backgroundColor = [UIColor whiteColor];
    _createClassView.isMessage = YES;
    
    _createClassView.isMessage = YES;
    _createClassView.fdbjName = self.cjClassName;
    _createClassView.fdbjId = self.fdbjId;
    _createClassView.className = @"成绩异常";
    
    
    [self.view addSubview:_createClassView];
    [_createClassView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@20);
        make.bottom.equalTo(@0);
    }];
    
    
}
#pragma mark - 获取成绩排名异常排名上升异常
-(void)getPaiMingChengJiYiChangUp{
    //http://apipad.mykeyu.cn/notice/NoticeReceiveService.svc
    isUp = YES;
    if (_model.msgId.length == 0||_model == nil) {
        _model = [XGMessageModelOfMe new];
        _model.msgId = @"757";
    }
    [self->_upArray removeAllObjects];
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"msgId":_model.msgId,@"isUp":@"1"};
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI sy_getNoticeReceiveServiceNoticeReceiveService:parama success:^(id  _Nonnull responseObject) {
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            CJPMYiChangModel *model = [CJPMYiChangModel yy_modelWithJSON:dic];
            [self->_upArray addObject:model];
            if (self->_className.text.length==0) {
                self->_className.text = model.ClassName;
                weakSelf.cjClassName = model.ClassName;
                weakSelf.fdbjId = model.ClassId;
            }
        }
        [NSObject executeRunloop:^{
            self->isUp = YES;
            [self->_tableView reloadData];
        } afterDelay:0.3];
        
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
         [MBProgressHUD mj_hideHUDForView:self.view];
        NSLog(@"成绩排名请求失败 %@",error.message);
    }];
    
}
#pragma mark - 获取成绩排名异常排名下降异常
-(void)getPaiMingChengJiYiChangDown{
    isUp = NO;
    if (_model.msgId.length == 0||_model == nil) {
        _model = [XGMessageModelOfMe new];
        _model.msgId = @"757";
    }
    //http://apipad.mykeyu.cn/notice/NoticeReceiveService.svc
    NSDictionary *parama = @{@"msgId":_model.msgId,@"isUp":@"0"};
    [self->_downArray removeAllObjects];
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI sy_getNoticeReceiveServiceNoticeReceiveService:parama success:^(id  _Nonnull responseObject) {
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            CJPMYiChangModel *model = [CJPMYiChangModel yy_modelWithJSON:dic];
            [self->_downArray addObject:model];
            if (self->_className.text.length==0) {
                self->_className.text = model.ClassName;
                weakSelf.cjClassName = model.ClassName;
                weakSelf.fdbjId = model.ClassId;
            }
        }
        [self->_tableView reloadData];
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        NSLog(@"成绩排名请求失败 %@",error.message);
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
